#pragma once
#include "Thread.hpp"
#include "Log.hpp"
#include <iostream>
#include <queue>
#include <vector>
#include <pthread.h>
#include <functional>
#include <unistd.h>
using namespace ThreadModule;

template<class T>
class ThreadPool
{
private:
    void Lock(pthread_mutex_t& mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void UnLock(pthread_mutex_t& mutex)
    {
        pthread_mutex_unlock(&mutex);
    }
    void Sleep(pthread_cond_t& cond, pthread_mutex_t& mutex)
    {
        pthread_cond_wait(&cond, &mutex);
    }
    void WakeUp(pthread_cond_t& cond)
    {
        pthread_cond_signal(&cond);
    }
    void WakeUpAll(pthread_cond_t& cond)
    {
        pthread_cond_broadcast(&cond);
    }
public:
    ThreadPool(int threadnum = 3)
        :_threadNum(threadnum), _waitNum(0), _isrunning(false)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
        LOG(INFO, "threadpool construct()");
    }
    void Run(const std::string& name)
    {
        while(true)
        {
            //加锁
           Lock(_mutex);
           //判断： 任务队列为空 且 程序正在运行
           while(_taskQueue.empty() && _isrunning)
           {
                _waitNum++;
                Sleep(_cond, _mutex);
                _waitNum--;
           }
           // 走到这里有3中情况
           // 1.任务为空 程序不在运行
           if(_taskQueue.empty() && !_isrunning)
           {
                UnLock(_mutex);
                break;
           }
           // 2.任务不为空 程序在运行
           // 3.任务不为空 程序再运行
           LOG(INFO, "%s get a task", name.c_str());
           T t = _taskQueue.front();
           _taskQueue.pop();
           UnLock(_mutex);

            //释放锁后，执行每个线程私有的任务
            t();
            LOG(INFO, "%s handler a task, result : %s", name.c_str(), t.ResultToString().c_str());
        }
    }
    void Init()
    {
        for (int i = 0; i < _threadNum; i++)
        {
            std::string name = "thread-" + std::to_string(i + 1);
            _threads.emplace_back(std::bind(&ThreadPool::Run, this, std::placeholders::_1), name);
        }
    }

    void Start()
    {
        _isrunning = true;
        for (auto& thread : _threads)
        {
            thread.Start();
            LOG(INFO, "%s is running...", thread.name().c_str());
        }
    }

    void Stop()
    {
        Lock(_mutex);
        _isrunning = false;
        //唤醒所有线程
        WakeUpAll(_cond);
        UnLock(_mutex);
    }

    bool Enqueue(const T& in)
    {
        bool ret = false;
        Lock(_mutex);
        if(_isrunning)
        {
            _taskQueue.emplace(in);
            //如果有等待线程，唤醒
            if(_waitNum > 0) 
                WakeUp(_cond);
            ret = true;
            LOG(INFO, "enqueue a task");
        }
        UnLock(_mutex);
        return ret;
    }
    void Wait()
    {
        for (auto& thread : _threads)
        {
            thread.Join();
            LOG(INFO, "%s is quit...", thread.name().c_str());
        }
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
private:
    int _threadNum;
    std::vector<Thread> _threads;
    std::queue<T> _taskQueue;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    int _waitNum;
    bool _isrunning;
};